package com.wang.vagus.service.impl;

import com.wang.vagus.exception.BaseException;
import com.wang.vagus.base.ResultEnum;
import com.wang.vagus.dao.UserRepository;
import com.wang.vagus.data.dto.LoginDTO;
import com.wang.vagus.data.dto.RegisterDTO;
import com.wang.vagus.entity.User;
import com.wang.vagus.service.UserService;
import com.wang.vagus.util.IdGenerator;
import com.wang.vagus.util.JwtTokenUtil;
import com.wang.vagus.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;
    @Autowired
    private IdGenerator idGenerator;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Value("${jwt.validity}")
    private long expireTime;

    @Override
    public User register(RegisterDTO registerDTO) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        User user = User.builder()
                .id(idGenerator.nextId())
                .name(registerDTO.getName())
                .password(registerDTO.getPassword())
                .createTime(timestamp)
                .updateTime(timestamp)
                .build();

        return userRepository.save(user);
    }

    @Override
    public String login(LoginDTO loginDTO) {
        String name = loginDTO.getName();
        String password = loginDTO.getPassword();
        User user = userRepository.findByName(name);
        if (user != null) {
            if (password.equals(user.getPassword())) {
                String token = jwtTokenUtil.generateToken(name);
                long id = user.getId();
                redisUtil.set("token:" + token, id, expireTime);
                return token;
            } else {
                throw new BaseException(ResultEnum.PASSWORD_ERROR);
            }
        } else {
            throw new BaseException(ResultEnum.USER_NOT_FOUND);
        }

    }

    @Override
    public User getUerInfoByToken(String toke) {
        Object o = redisUtil.get("token:" + toke);
        if (o != null) {
            long id = (long) o;
            return userRepository.findById(id);
        } else {
            return null;
        }

    }
}
